package org.mybatis.c3p0;

import static org.apache.ibatis.io.Resources.getResourceAsReader;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class SetupC3p0Xml {

	/**
	 * @param args
	 * @throws SQLException 
	 */
	public static void main(String[] args) throws SQLException {
		// TODO Auto-generated method stub

		try {

			String resource = "org/mybatis/c3p0/mybatis-config.xml";

			InputStream inputStream = Resources.getResourceAsStream(resource);
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	        Environment environment = sqlSessionFactory.getConfiguration().getEnvironment();
			DataSource dataSource = environment.getDataSource();
//			
//			ScriptRunner runner = new ScriptRunner(dataSource.getConnection());
//			runner.setAutoCommit(true);
//			runner.setStopOnError(true);
//			runner.runScript(new FileReader("config/database-schema.sql"));
//			runner.runScript(new FileReader("config/database-test-data.sql"));
//			runner.closeConnection();

			SqlSession ss = sqlSessionFactory.openSession();

			Account a = ss.selectOne("example.getAccountById", 1);

			System.out.println(a.getFirstName());

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
